package com.example.mainserver.service;
import java.util.Date;

import com.example.common.model.Emp;
import com.example.common.model.MailConstants;
import com.example.common.model.MailSendLog;
import com.example.mainserver.mapper.EmpMapper;
import com.example.mainserver.mapper.MailSendLogMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.UUID;

@Service
@Validated
public class EmpService {

    private static final Logger logger = LoggerFactory.getLogger(EmpService.class);

    @Autowired
    EmpMapper empMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    MailSendLogMapper mailSendLogMapper;

    /**
     * 入职成功（添加员工），发送邮箱
     */
    public void addEmp(@Valid Emp emp){
        int res = empMapper.add(emp);
        if (res == 1){
            // 在消息发送的时候，我们就往该表中保存一条消息发送记录，并设置状态 status 为 0，count为 0，tryTime 为 1 分钟之后。
            String msgId = UUID.randomUUID().toString();
            logger.info("消息唯一id，msgId = {}",msgId);
            MailSendLog mailSendLog = new MailSendLog();
            mailSendLog.setMsgId(msgId);
            mailSendLog.setEmpId(emp.getId());
            mailSendLog.setStatus(MailConstants.DELIVERING);
            mailSendLog.setRoutingKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailSendLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            mailSendLog.setTryTime(new Date(System.currentTimeMillis() + MailConstants.MSG_TIMEOUT * 1000 * 60));
            mailSendLogMapper.insert(mailSendLog);
            // 关联数据携带 msgId 唯一标识这条消息
            CorrelationData correlationData = new CorrelationData(msgId);
            //添加成功，给 mq 发送 一条发送邮件的消息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME
                    , emp,correlationData);
        }

    }

}
